package org.mbcorp.sar.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

import org.mbcorp.sar.model.CalendarioJsonDTO;
import org.mbcorp.sar.model.Fase;
import org.mbcorp.sar.model.FiltroBusqueda;
import org.mbcorp.sar.service.AlertaService;
import org.mbcorp.sar.service.FaseService;
import org.mbcorp.sar.service.HorarioService;
import org.mbcorp.sar.validator.FiltroBusquedaValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.MessageSource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

@PreAuthorize(value = "hasRole('ROLE_COORDINADOR')")
@Controller
public class ActivarFaseController {

	@Autowired
    private MessageSource messageSource;
	
	@Autowired
	private FaseService faseService;
	
	@Autowired
	private HorarioService horarioService;
	
	@Autowired
	private AlertaService alertaService;
	
	@Autowired
	private FiltroBusquedaValidator filtroBusquedaValidator;
	
	@InitBinder
	public void initDateBinder(final WebDataBinder dataBinder, final Locale locale) {
	    final String dateformat = this.messageSource.getMessage("date.format", null, locale);
	    final SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
	    sdf.setLenient(false);
	    dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
	}

	@RequestMapping(value = "/activarFase", method = RequestMethod.GET)
	public String buscarFasesPrioritarias(FiltroBusqueda filtroBusqueda, Model model) {
			List<Fase> listaPrioritarios = faseService.buscarFasesVencidas();
			if(!listaPrioritarios.isEmpty()){
				model.addAttribute("tienePrioritarios", true);
			}
			model.addAttribute("listaFases", listaPrioritarios);
		return "activarFase";
	}
	
	@RequestMapping(value = "/consultarFasesInactivas", method = RequestMethod.POST)
	public String mostrarResultados(Model model, FiltroBusqueda filtroBusqueda, BindingResult result) {
		if(!filtroBusquedaValidator.validarRangoFechas(filtroBusqueda, result)){
			model.addAttribute("flagError", true);
			return buscarFasesPrioritarias(filtroBusqueda, model);		
			}
		List<Fase> listaFases = faseService.buscarInactivas(filtroBusqueda);
		model.addAttribute("listaFases", listaFases);
		return "activarFase";
	}
	
	@RequestMapping(value = "/getCalendarioFase/{id}", method = RequestMethod.GET)
    public @ResponseBody String getFechas(HttpServletResponse response, @PathVariable Integer id) {
		Fase fase = faseService.buscarPorId(id);
        List<CalendarioJsonDTO> listaHorario= horarioService.armarCalendarioFase(fase);		
        // Convert to JSON string.
        String json = new Gson().toJson(listaHorario);

        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        System.out.println(json);
        return json;
    }
	
	@RequestMapping(value = "/activarFase/{idFase}", method = RequestMethod.GET)
	public String activarFase(FiltroBusqueda filtroBusqueda, Model model, @PathVariable("idFase") Integer idFase) {
		Fase f = faseService.buscarPorId(idFase);
		faseService.activarFase(f);
		alertaService.mandarAlertaOperadores(f);
		model.addAttribute("faseActivada", f.getNombre() + " de la solicitud " + f.getSolicitud().getId());
		return "activarFase";
	}	
	
}
